import os
import subprocess


from libqtile import bar, layout, widget, extension
from libqtile.config import Click, Drag, Group, Key, Match, Screen
from libqtile.lazy import lazy
from libqtile.command import lazy
from libqtile.utils import guess_terminal
from libqtile import hook
from libqtile.log_utils import logger

mod = "mod4"

@hook.subscribe.startup_once
def autostart():
    home = os.path.expanduser('/home/dovi/.config/qtile/autostart.sh')
    subprocess.Popen([home])

## СДЕЛАТЬ ДИАЛОГОВЫЕ ОКНА ПЛАВАЮЩИМИ ----------------------------------------------
@hook.subscribe.client_new
def floating_dialogs(window):
    dialog = window.window.get_wm_type() == 'dialog'
    transient = window.window.get_wm_transient_for()
    if dialog or transient:
        window.floating = True

keys = [
    # Фокус
    Key([mod], "h", lazy.layout.left(), desc="Move focus to left"),
    Key([mod], "l", lazy.layout.right(), desc="Move focus to right"),
    Key([mod], "j", lazy.layout.down(), desc="Move focus down"),
    Key([mod], "k", lazy.layout.up(), desc="Move focus up"),
    
    # Перемещение окон
    Key([mod, "shift"], "h", lazy.layout.shuffle_left(), desc="Move window to the left"),
    Key([mod, "shift"], "l", lazy.layout.shuffle_right(), desc="Move window to the right"),
    Key([mod, "shift"], "j", lazy.layout.shuffle_down(), desc="Move window down"),
    Key([mod, "shift"], "k", lazy.layout.shuffle_up(), desc="Move window up"),
    
    # Убийство, полныйэкран, преключения режимов, перезапуск конфига
    Key([mod], "f", lazy.window.toggle_floating()),
    Key([mod], "g", lazy.window.toggle_fullscreen()),
    Key([mod, "shift"], "c", lazy.window.kill(), desc="Kill focused window"),
    Key([mod, "control"], "r", lazy.reload_config(), desc="Reload the config"),
    Key(["mod1"], "space", lazy.widget["keyboardlayout"].next_keyboard(), desc="Keyboard"),
    
    # Dmenu и все что с ним связано
    Key([mod], "r", lazy.spawn("dmenu_run -nb #151515 -nf #ffffff -sf #589cc5 -sb #1a1a1a ")),
    Key([mod, "shift"], "e", lazy.spawn("/home/dovi/.config/qtile/dmenupowermenu")),
    Key([mod, "shift"], "r", lazy.spawn("/home/dovi/.config/qtile/dmenuapplication")),
    # Звук
    Key([], "F4", lazy.spawn("pactl set-sink-mute 0 toggle")),
    Key([], "F3", lazy.spawn("pactl set-sink-volume 0 +5%")),
    Key([], "F2", lazy.spawn("pactl set-sink-volume 0 -5%")),

    # Переход между мониторами
    Key([mod], 't', lazy.next_screen(), desc='Next monitor'),

    # Запуск приложении
    Key([mod], "Return", lazy.spawn("alacritty")),
    Key([],"Print", lazy.spawn("flameshot gui")),
    Key([mod,"shift"], "t", lazy.spawn("telegram-desktop")),
    Key([mod,"shift"], "n", lazy.spawn("alacritty -e ranger")),
    Key([mod,"shift"], "l", lazy.spawn("librewolf")),
    Key([mod,"shift"], "b", lazy.spawn("torbrowser-launcher")),
]
groups = [Group(i) for i in "123456"]
groups = [                                                                 
    Group("1", label = "", matches=[Match(wm_class=["Firefox"])]),
    Group("2", label = ""),
    Group("3", label = ""),
    Group("4", label = "", matches=[Match(wm_class=["discord"])]),
    Group("5", label = "", matches=[Match(wm_class=["krita"])]),
    Group("6", label = ""),
]                                                        
for i in groups:
    keys.extend(
        [
            # mod1 + letter of group = switch to group
            Key(
                [mod],
                i.name,
                lazy.group[i.name].toscreen(),
                desc="Switch to group {}".format(i.name),
            ),
         
           Key(
                [mod, "shift"],
                i.name,
                lazy.window.togroup(i.name, switch_group=True),
                desc="Switch to & move focused window to group {}".format(i.name),
           ),
        ]
    )

layouts = [
    layout.MonadTall(border_focus = "#000000", border_normal = "ffffff", border_width=1),
]

widget_defaults = dict(
    font='JetBrainsMono',
    fontsize=14,
    padding=8,
)
extension_defaults = widget_defaults.copy()

screens = [

    Screen(
        top=bar.Bar(
            [
                widget.GroupBox( # Толщина рамки
                    highlight_method='line', # Метод выделения активного воркспейса
                    highlight_color='#263238',# Цвет текста активного воркспейса
                    inactive='#008DD0'            
                        ),
                widget.Prompt(), # Виджет выполнения команд

                widget.WindowName(
                    max_chars=30
                    ),

                widget.Chord(
                    chords_colors={
                        "launch": ("#ff0000", "#ffffff"),
                    },
                    name_transform=lambda name: name.upper(),
                ),

                widget.OpenWeather(
                    location='Khabarovsk',
                    format='  {main_temp}°'
                    ),

                widget.Spacer(length=650),

                widget.KeyboardLayout(
                    configured_keyboards=['us', 'ru']
                    ),
                widget.Systray(),
                widget.Clock(format="%Y-%m-%d %a %H:%M %p",
                             padding = 5
                             ),
            ],
            24,
            border_width=[5, 5, 5, 5],  # Draw top and bottom borders
            border_color=["263238", "263238", "263238", "263238"],
            margin = 0,
            background="#263238"# Borders are magenta
        ),
        ),
    Screen(
        top=bar.Bar(
            [
                widget.GroupBox( # Толщина рамки
                    highlight_method='line', # Метод выделения активного воркспейса
                    highlight_color='#263238',# Цвет текста активного воркспейса
                    inactive='#008DD0'            
                        ),
                widget.WindowName(
                    max_chars=30
                    ),

                widget.Chord(
                    chords_colors={
                        "launch": ("#ff0000", "#ffffff"),
                    },
                    name_transform=lambda name: name.upper(),
                ),

                widget.OpenWeather(
                    location='Khabarovsk',
                    format='  {main_temp}°'
                    ),

                widget.Spacer(length=650),

                widget.KeyboardLayout(
                    configured_keyboards=['us', 'ru']
                    ),
                widget.Clock(format="%Y-%m-%d %a %H:%M %p",
                             padding = 5
                             ),
            ],
            24,
            border_width=[5, 5, 5, 5],  # Draw top and bottom borders
            border_color=["263238", "263238", "263238", "263238"],
            margin = 0,
            background="#263238"# Borders are magenta
        ),
        y=600
    ),
    ]
# Мышка
mouse = [
    Drag([mod], "Button1", lazy.window.set_position_floating(), start=lazy.window.get_position()),
    Drag([mod], "Button1", lazy.window.set_position(), start=lazy.window.get_position()),
    Drag([mod], "Button3", lazy.window.set_size_floating(), start=lazy.window.get_size()),
    Click([mod], "Button2", lazy.window.bring_to_front()),
]

dgroups_key_binder = None
dgroups_app_rules = []  
follow_mouse_focus = True
bring_front_click = False
cursor_warp = True
floating_layout = layout.Floating(
        border_width=2,
        border_focus="#ffffff",
    float_rules=[
        *layout.Floating.default_float_rules,
    ]
)
auto_fullscreen = True
focus_on_window_activation = "smart"
reconfigure_screens = True

auto_minimize = False

wl_input_rules = None

wmname = "Qtile"

